import { ref, computed } from "vue";
import { defineStore } from "pinia";
import storage from "@/storage";
import { StorageConst } from "@/constant";
import { useRoute, useRouter, type RouteRecordRaw } from "vue-router";
import RouterContainer from '@/components/router-container.vue'
import type { IUpdateRouter } from "@/types/router-interface";
import DynamicRouterHelper from "@/common/dynamicRouterHelper";
import type { SysMenu } from "@/openapi-generator";
import type { PageRecord } from "@/types/page-record";
import type { SysMenuEx } from "@/types/sys-menu-tree";

/**
* 加载菜单列表
* @returns 
*/
export const loadMenuList = async (keyword: string = "", page: number = 1, size: number = 9999): Promise<PageRecord<SysMenu>> => {
  // 组装菜单为树结构
  let res;
  let pageRecord: PageRecord<SysMenuEx> = {
    current: 1,
    size: 10,
    total: 0,
    pages: 0,
    records: []
  }

  try {
    res = await $adminApi.sysMenuList(keyword, page, size);
  } catch (error) {
    console.log("读取系统菜单失败" + error);
    return pageRecord;
  }

  // 递归组装树结构
  pageRecord.current = res.data.current;
  pageRecord.size = res.data.size;
  pageRecord.total = res.data.total;
  pageRecord.pages = res.data.pages;
  pageRecord.records = DynamicRouterHelper.handlerTree(res.data.records);
  return pageRecord;
}

export const useMenuStore = defineStore("menu", () => {
  const route = useRoute();
  const router = useRouter();
  const menuList = ref<SysMenuEx[]>([]);

  const currentRouteId = computed(() => {
    return queryRouteId(menuList.value);
  });

  // 递归查询路由id
  const queryRouteId = (menus: any[]): number => {
    for (let index = 0; index < menus.length; index++) {
      const x = menus[index];

      if (x.path == route.fullPath) {
        return x.id;
      }

      if (x.children && x.children.length) {
        const id = queryRouteId(x.children);
        if (id) {
          return id;
        }
      }
    }

    return 0;
  }

  /**
   * 重新加载菜单
   */
  const reloadMenu = async () => {
    let res;

    try {
      res = await loadMenuList();
    } catch (error) {
      return
    }

    setMenu(res.records);
  }

  /**
   * 设置菜单
   * @param data SysMenuTreeVo[]
   */
  const setMenu = (data: SysMenuEx[]) => {
    menuList.value = data;
  }

  /**
   * 更新路由记录
   */
  const updateRouterRecord = (routerParam: IUpdateRouter) => {
    // const frontEndRouter = routerParam.frontEndRouter;
    // const parent = DynamicRouterHelper.findById(routerParam.parentId, menuList.value);
    // const path = DynamicRouterHelper.splicePath([parent?.frontEndRouter || "", frontEndRouter]);
    // const name = DynamicRouterHelper.pathToName(path);
    // const parentName = DynamicRouterHelper.pathToName(parent?.frontEndRouter || "");
    // const component = routerParam.path;
    // const asyncComponent = () => import(/* @vite-ignore */`/src/views/${component}.vue`);
    // const record: RouteRecordRaw = {
    //   path,
    //   name,
    //   component: () => component ? asyncComponent : RouterContainer,
    //   meta: routerParam.meta
    // };
    // // 添加路由时 存在相同name的路由会作先删除后添加的操作 这里不用管是更新还是新增
    // parentName ? router.addRoute(parentName, record) : router.addRoute(record);
  }

  /**
   * 按ID删除路由记录
   * @param id 
   */
  const removeRouterRecordById = (id: number) => {
    const find = DynamicRouterHelper.findById(id, menuList.value);
    router.removeRoute(DynamicRouterHelper.pathToName(find?.frontEndRouter || ""));
  }

  // 获取菜单
  const menu = computed(() => menuList);

  return {
    currentRouteId,
    menu,
    updateRouterRecord,
    removeRouterRecordById,
    setMenu,
    reloadMenu
  };
});
